package org.game.gobang.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.game.constant.APIConstant;
import org.game.gobang.server.init.GobangServerInitializer;
import org.game.util.MapUtil;
import org.game.util.YamlUtil;

import java.util.Map;

@Slf4j
public class GobangServer {
    private int port;

    public GobangServer(int port) {
        this.port = port;
    }

    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(boss, worker)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new GobangServerInitializer());

            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
            log.info("服务器启动 启动端口 : " + port);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> config = YamlUtil.read("gobang\\gobang-server\\src\\main\\resources\\application.yml");
        MapUtil.cloneMap(APIConstant.CONFIG, config);
        GobangServer server = new GobangServer((int) APIConstant.CONFIG.get("port"));
        server.start();
    }
}
